// $Rev: 130 $

#include <fstream>
#include "file_index.h"
#include "constants.h"
#include "util.h"

using namespace std;

FileIndex::FileIndex(string config_file) {
	string md5, name;
	int size;	
	if (config_file.empty()) return;
	ifstream fin(config_file.c_str());
	if (!fin.is_open()) {
		error("Couldn't open index database");
		return;
	}
	int numfiles = 0;
	fin >> numfiles;
	for (int i = 0; i < numfiles; i++) {
		fin >> md5;
		fin.ignore(100, '\n');
		getline(fin, name);
		log (md5 + " " + name);
		File *file = new File(md5, name);
		fin >> size;
		file->set_file_size(size);
		for (int f = 0; f < (size + BLOCK_SIZE - 1)/BLOCK_SIZE; f++) {
			fin >> md5;
			file->add_fragment(new Fragment(md5));
		}
		add_file(file);
	}
	fin.close();
}

void FileIndex::add_file(const File *file) {
	for (size_t i = 0; i < files.size(); i++) {
		if (files[i]->get_md5() == file->get_md5()) {
			delete file;
			return;
		}
	}
	files.push_back(file);
}

const vector<const File *> &FileIndex::get_files() const {
	return files;
}

const File *FileIndex::get_file_by_md5(string md5) const {
	for (size_t i = 0; i < files.size(); i++) {
		if (files[i]->get_md5() == md5) {
			return files[i];
		}
	}
	return 0;
}

FileIndex::~FileIndex() {
	ofstream fout(DEFAULT_CONFIG);
	fout << files.size() << endl;
	for (size_t i = 0; i < files.size(); i++) {
		fout << files[i]->get_md5() << endl;
		fout << files[i]->get_name() << endl;
		fout << files[i]->get_size() << endl;
		const vector<Fragment *> &fragments = files[i]->get_fragments();
		for (size_t f = 0; f < fragments.size(); f++) {
			fout << fragments[f]->get_md5() << endl;;
		}
		delete files[i];
	}
	fout.close();
}
